package com.luo.comm.vo;

import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;

/**
 * 返回对象。主要供controller返回给前端用。也可以用于各服务层返回给controller用。
 * */

@Data
public class Result {

    private Integer code;

    @JsonInclude(JsonInclude.Include.NON_NULL) // 当为空时不转换JSON输出。这样前端就不会返回null.
    private Object data;

    @JsonInclude(JsonInclude.Include.NON_NULL) // 当为空时不转换JSON输出。这样前端就不会返回null.
    private String msg;

    public Result() {
        MyResEnum success = MyResEnum.SUCCESS; // 默认是正常
        this.code = success.getCode();
        this.msg =success.getMsg();
    }

    public Result(Object data) {
        MyResEnum success = MyResEnum.SUCCESS; // 默认是正常
        this.code = success.getCode();
        this.msg = success.getMsg();
        this.data = data;
    }

    public Result(MyResEnum myHttpEnum, Object data) {
        this.code = myHttpEnum.getCode();
        this.msg = myHttpEnum.getMsg();
        this.data = data;
    }

    public Result(MyResEnum myHttpEnum, Object data, String msg) {
        this.code = myHttpEnum.getCode();
        this.msg = msg;
        this.data = data;
    }

    public Result(MyResEnum myHttpEnum) {
        this.code = myHttpEnum.getCode();
        this.msg = myHttpEnum.getMsg();
        this.data = null;
    }

    public Result(Integer code, Object data, String msg) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    // 标准方法1成功。接收一个自定义的data，返回成功状态和消息。
    public static Result success(Object data) {
        return new Result(MyResEnum.SUCCESS.getCode(), data, MyResEnum.SUCCESS.getMsg());
    }

    // 标准方法2-失败，返回失败状态和消息，data为空。
    public static Result fail(String msg) {
        return new Result(MyResEnum.FAIL.getCode(), null, msg);
    }

    // 标准方法3-错误，返回失败状态和消息，data为空。
    public static Result error(String msg) {
        return new Result(MyResEnum.FAIL.getCode(), null, msg);
    }


    // 按枚举类的code返回。 ResultsObj.byCode(1000)。尽量少用，需要自行处理 IllegalArgumentException
    public static Result byCode(Integer code) {
        MyResEnum myResEnum = MyResEnum.byCode(code);
        return new Result(myResEnum.getCode(), null, myResEnum.getMsg());
    }

}
